package com.isoft.c2team3service2.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.isoft.c2team3service2.config.MinioProperties;
import com.isoft.c2team3service2.entity.Head;
import com.isoft.c2team3service2.entity.Person;
import com.isoft.c2team3service2.entity.Post;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.mapper.HeadMapper;
import com.isoft.c2team3service2.mapper.PersonMapper;
import com.isoft.c2team3service2.mapper.PostMapper;
import com.isoft.c2team3service2.service.FileService;
import com.isoft.c2team3service2.util.UserHolder;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 蓝莓
 * @date 2025/6/20 13:37
 */
@Service
public class FileServiceImp implements FileService {

    @Autowired
    private MinioProperties properties;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private MinioClient client;

    @Autowired
    private HeadMapper headMapper;

    @Autowired
    private PersonMapper personMapper;

//    //上传文件
//    @Override
//    public String upload(MultipartFile file) {
//        String join = null;
//
//        try {
//            boolean bucketExists = client.bucketExists(BucketExistsArgs.builder()
//                    .bucket(properties.getBucketName()).build());
//            if (!bucketExists) {
//                client.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
//                client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName()).config(createBucketPolicyConfig(properties.getBucketName())).build());
//            }
//
//            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
//
//            //获取文件后缀名
//            String originalFilename = file.getOriginalFilename();
//            if (originalFilename !=null && "mp4".equals(originalFilename.substring(originalFilename.lastIndexOf(".")))) {
//                filename = "video" +  new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
//            }
//
//            client.putObject(PutObjectArgs.builder().
//                    bucket(properties.getBucketName()).
//                    object(filename).
//                    stream(file.getInputStream(), file.getSize(), -1).
//                    contentType(file.getContentType()).build());
//
//            join = String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);
//
//            UserDTO user = UserHolder.getUser();
//            Integer id = user.getId();
//
//            Post p = new Post();
//            p.setPhotoUrl(join);
//            p.setUserId(id);
//            postMapper.update(new LambdaUpdateWrapper<Post>()
//                .eq(Post::getId, id)
//                .set(Post::getPhotoUrl, join));
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        return join;
//    }

//    //    上传头像
//    @Override
//    public String rePhoto(MultipartFile file, String email) {
//        String join = null;
//        try {
//            boolean bucketExists = client.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
//            if (!bucketExists) {
//                client.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
//                client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName()).config(createBucketPolicyConfig(properties.getBucketName())).build());
//            }
//
//            String filename =  "head" + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
//            client.putObject(PutObjectArgs.builder().
//                    bucket(properties.getBucketName()).
//                    object(filename).
//                    stream(file.getInputStream(), file.getSize(), -1).
//                    contentType(file.getContentType()).build());
//
//            join = String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);
//
//            Head head = new Head();
//            head.setEmail(email);
//            head.setPhotourl(join);
//            headMapper.insert(head);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        return join;
//    }

    /**
     * 通用文件上传方法
     * @param file 上传的文件
     * @param type 文件类型，如 "video", "head", "background"
     * @return 文件的完整访问 URL
     * @throws Exception 上传过程中发生的异常
     */
    private String uploadFile(MultipartFile file, String type) throws Exception {
        // 1. 检查并创建 bucket（如果不存在）
        boolean bucketExists = client.bucketExists(BucketExistsArgs.builder()
                .bucket(properties.getBucketName())
                .build());
        if (!bucketExists) {
            client.makeBucket(MakeBucketArgs.builder()
                    .bucket(properties.getBucketName())
                    .build());
            client.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(properties.getBucketName())
                    .config(createBucketPolicyConfig(properties.getBucketName()))
                    .build());
        }

        // 2. 生成文件路径：type/yyyyMMdd/uuid-filename
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            originalFilename = "unknown";
        }

        // 清理文件名中的非法字符（防注入/兼容性）
        originalFilename = originalFilename.replaceAll("[^a-zA-Z0-9._-]", "_");

        String uuidName = UUID.randomUUID() + "-" + originalFilename;
        String objectName = String.join("/", type, dateStr, uuidName);

        // 3. 执行上传
        client.putObject(PutObjectArgs.builder()
                .bucket(properties.getBucketName())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build());

        // 4. 返回完整 URL
        return String.join("/", properties.getEndpoint(), properties.getBucketName(), objectName);
    }

    //上传文件
    @Override
    public String upload(MultipartFile file) {
        try {
            // 根据后缀判断类型，默认是 "image"
            String type = "image";
            String originalFilename = file.getOriginalFilename();
            if (originalFilename != null && originalFilename.endsWith(".mp4")) {
                type = "video";
            }

            String fileUrl = uploadFile(file, type);

            // 更新数据库
            UserDTO user = UserHolder.getUser();
            Integer userId = user.getId();

            postMapper.update(
                    new LambdaUpdateWrapper<Post>()
                            .eq(Post::getId, userId)
                            .set(Post::getPhotoUrl, fileUrl)
            );

//
//            Post p = new Post();
//            p.setPhotoUrl(fileUrl);
//            p.setUserId(userId);
//            postMapper.update(new LambdaUpdateWrapper<Post>()
//                .eq(Post::getId, userId)
//                .set(Post::getPhotoUrl, fileUrl));

            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
//    上传头像
    @Override
    public String rePhoto(MultipartFile file, String email) {
        try {
            String fileUrl = uploadFile(file, "head");

            Head head = new Head();
            head.setEmail(email);
            head.setPhoto(fileUrl);
            head.setUserId(UserHolder.getUser().getId());
            headMapper.insert(head);

            return fileUrl;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private String createBucketPolicyConfig(String bucketName) {

        return """
                  {
                    "Statement" : [ {
                      "Action" : "s3:GetObject",
                      "Effect" : "Allow",
                      "Principal" : "*",
                      "Resource" : "arn:aws:s3:::%s/*"
                    } ],
                    "Version" : "2012-10-17"
                  }
                  """.formatted(bucketName);
    }

    public String background(String background, MultipartFile file,Integer id) {
        try {
            String fileUrl = uploadFile(file, background);

            Person person = new Person();
            person.setBackground(fileUrl);
            personMapper.update(person,new LambdaUpdateWrapper<Person>()
                    .eq(Person::getId, id));

            return fileUrl;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String upLoadName(String name, MultipartFile file) {
        try {
            String s = uploadFile(file, name);
            return s;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String upPostPhoto(MultipartFile file, String name) {
        try {
            return  uploadFile(file, name);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String updatePhoto(MultipartFile file, String email) {

        try {
            String fileUrl = uploadFile(file, "head");

           return headMapper.updateHead(fileUrl, email) > 0 ? "更新成功" : "更新失败";


        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
